package com.metadata_system.common.service;

import com.alibaba.fastjson.JSON;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.exception.TranslateException;
import com.metadata_system.common.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
public class MyLibretranslateService {
    @Value("${translate.url}")
    private String baseUrl;

    /**
     * 通用翻译方法
     * @param text 要翻译的文本
     * @param sourceLang 源语言代码 (zh/en等)
     * @param targetLang 目标语言代码 (zh/en等)
     * @return 翻译结果
     * @throws TranslateException 翻译异常
     */
    public ApiResult translate(String text, String sourceLang, String targetLang) throws TranslateException {
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("q", text);
        map.add("source", sourceLang);
        map.add("target", targetLang);
        map.add("format", "text");
        ApiResult apiResult = HttpUtil.httpPost(baseUrl, map);
        if (apiResult.getCode() != 0) {
            throw new TranslateException(apiResult.getMessage());
        }
        return ApiResult.success(JSON.parseObject(apiResult.getData().toString()).get("translatedText").toString());
    }

}